package cn.steam.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

import static com.sun.xml.internal.ws.commons.xmlutil.Converter.UTF_8;

/**
 * @author zhang jintao on 2022/08/24
 **/
@Component
@Slf4j
public class RequestFilter extends OncePerRequestFilter {

    @SuppressWarnings("NullableProblems")
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 包装HttpServletRequest，把输入流缓存下来
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
        // 包装HttpServletResponse，把输出流缓存下来
        ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
        filterChain.doFilter(wrappedRequest, wrappedResponse);
        String queryString = wrappedRequest.getQueryString();
        if (!StringUtils.isEmpty(queryString)) {
            log.info("http request,queryString:{}", URLDecoder.decode(queryString, UTF_8));
        }
        log.info("http request:{}", new String(wrappedRequest.getContentAsByteArray()));
        log.info("http response:{}", new String(wrappedResponse.getContentAsByteArray()));
        // 注意这一行代码一定要调用，不然无法返回响应体
        wrappedResponse.copyBodyToResponse();


    }
}
